import cgi, urllib, logging
from django.utils import simplejson
from google.appengine.api import urlfetch

class BitLy():
	def __init__(self, login, apikey):
		self.login = login
		self.apikey = apikey

	def shorten(self,longUrl):
		longUrl = urllib.quote_plus(longUrl)
		request = "http://api.bit.ly/v3/shorten?longUrl=" + longUrl
		request += "&domain=bit.ly" + "&login=" + self.login + "&apiKey=" +self.apikey
		result = urlfetch.fetch(request)
		logging.error(result.content);
		json = simplejson.loads(result.content)
		return json['data']['url']

	def expand(self,shortUrl):
		request = "http://api.bit.ly/v3/expand?shortUrl=" + shortUrl
		request += "&login=" + self.login + "&apiKey=" +self.apikey
		result = urlfetch.fetch(request)
		json = simplejson.loads(result.content)
		logging.error(result.content);
		return json['data']['long_url']
